import datetime

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

from .RBAC import RBAC, Queue
from .Ser import *
# Create your views here.
from .db import Dd


class User_M(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        data = User.objects.filter(username=username).first()
        if data and (data.password, password):
            return Response({'code': 200, 'msg': '登录成功'})
        else:
            return Response({'code': 10010, 'msg': '登录失败'})


class Youhui_M(APIView):
    def post(self, request):
        data = Youhui_Ser(data=request.data)
        if data.is_valid():
            data.save()
            return Response({'code': 200, 'msg': '添加成功'})
        else:
            return Response({'code': 10010, 'msg': '添加失败'})

    def get(self, request):
        data = Youhui.objects.all()
        all = Youhui_Ser(data, many=True)
        return Response(all.data)


import uuid


class UserYouhui_M(APIView):
    def post(self, request):
        user = request.data.get('user')
        youhui = request.data.get('youhui')
        uuids = str(uuid.uuid1())
        nudata = UserYouhui.objects.filter(user=user, youhui=youhui).first()
        if nudata:
            return Response({'code': 10010, 'msg': '已领取'})
        datas = Youhui.objects.filter(id=youhui).first()
        data1 = {'user': user,
                 'youhui': youhui,
                 'uuid': uuids,
                 'start_time': datas.start_time,
                 'end_time': datas.end_time,
                 'price': datas.price,
                 'name': datas.name}
        all = UserYous_Ser(data=data1)
        if all.is_valid():
            datas.count -= 1
            datas.save()
            all.save()
            return Response({'code': 100103})
        else:
            print(all.errors)
            return Response({'code': 500})

    def get(self, request):
        user = request.GET.get('user')
        price = request.GET.get('price')

        datetimes = datetime.datetime.now()

        data = UserYouhui.objects.filter(user=user, price__lt=price, start_time__lt=datetimes,
                                         end_time__gt=datetimes).all()
        all = UserYouhui_Ser(data, many=True)
        return Response({'code': '200', 'list': all.data})


from dwebsocket.decorators import accept_websocket
from django.http import HttpResponse, JsonResponse
import json

# 存储连接websocket的用户
websocketlist = []


@accept_websocket
def websocketLink(request):
    # 获取连接
    if request.is_websocket:
        # 新增 用户  连接信息
        websocketlist.append(request.websocket)
        # 监听接收客户端发送的消息 或者 客户端断开连接
        for message in request.websocket:
            break


# 发送消息
def websocketMsg(client, msg):
    b1 = json.dumps(msg, ensure_ascii=False).encode('utf-8')
    client.send(b1)


import time


# 服务端发送消息
def send():
    # data = request.POST
    # print(data)
    if websocketlist:
        for i in websocketlist:
            mes = [{'name': int(time.time())}]
            b1 = json.dumps(mes, ensure_ascii=False).encode('utf-8')
            i.send(b1)
    return HttpResponse("ok")


from apscheduler.schedulers.background import BackgroundScheduler


def testap(request):
    # 调度器
    scheduler = BackgroundScheduler()
    # 任务存储   seconds 每秒动用多少次
    scheduler.add_job(send, 'interval', seconds=1)
    scheduler.start()
    return HttpResponse("ok")


import time
import redis


# class GET_get(APIView):
def get_dese(request):
    db = Dd()
    res = db.get_all(
        "select customer.name,customer.tmoney,customer.compay_name,customer.state,customer.id,customer_manager.name as se from customer inner join reg_form on customer.reformid=reg_form.id inner join customer_manager on customer_manager.id=customer.manager_id")
    return JsonResponse({'code': '200', 'list': res})


def post_subimet(request):
    data = request.POST
    db = Dd()
    # 修改状态
    db.update(
        "update customer set state = %s,audit_time=%s,audit_name='zs' where id=%s" % (
        data['radio'], int(time.time()), data['id']))
    if int(data['radio']) == 2:
        # 查询相对应的服务 提交审核
        res = db.get_one("select * from customer where id=%s" % (data['id']))
        # 修改审核机构数量
        db.update("update reg_form set tcount=tcount+1 where id=%s" % res['reformid'])
        # 修改客户经理金额
        db.update("update customer_manager set tmoney=tmoney+%s where id=%s" % (res['tmoney'], res['manager_id']))
        # manager_id
    return JsonResponse({'code': '200'})


def getmes(request):
    db = Dd()
    res = db.get_all('select name,tcount as value from reg_form')
    print(res)
    return JsonResponse({"code": 200, 'list': res})


from app01.RBAC import RedisCon


# 元旦作业
# 登录
def inte_login(request):
    data = request.POST
    db = Dd()
    res = db.get_one(
        "select * from novel_user where username='%s' and password='%s'" % (data['username'], data['password']))
    if res['roleid'] == 2:
        print('999')
        r = RedisCon()
        r.insert_zes('audit', res['id'])
        print('888')
    if res:
        return JsonResponse({'code': '200', 'userid': res['id'], 'username': res['username'], 'msg': '登录成功'})
    else:
        return JsonResponse({'code': '403', 'msg': '用户登录失败'})


# 获取小说内容
def get_inneroal(request):
    db = Dd()
    res = db.get_all("select * from novel_table")
    return JsonResponse({'code': '200', 'res': res})


# 发布小说
def post_xiaoshuo(request):
    data = request.POST
    db = Dd()
    db.insert("insert into novel_table (name,userid) values ('%s',%s)" % (data['name'], data['userid']))
    r = RedisCon()
    r_list = r.get_all('audit')
    res_dta = db.get_one("select * from novel_table where name='%s'" % data['name'])
    queue = Queue()
    min = 0
    auditid = -1
    sum = 0
    if r_list:
        for i in r_list:
            count = queue.get_len_queue('auditlis%s' % i)
            if count == 0:
                min = count
                auditid = i
                sum = 0
            if min > count:
                min = count
                auditid = i
            sum += 1
        if int(auditid) > 0:
            print('111')
            print('111')
            sends(None,auditid)
            print('999')
            print('999')
            queue.set_insert('auditlis%s' % auditid, res_dta['id'])
    else:
        return JsonResponse({'code': '200', 'msg': '没有审核员'})
    return JsonResponse({'code': 200, 'msg': '添加成功'})


# 更改小说审核状态
# 获取小说内容
def update_inneroal(request):
    data = request.GET
    db = Dd()
    if int(data['pid']) == 2:
        # 更改小说状态  如果通过时
        db.update("update novel_table set state=%s where id=%s" % (data['pid'], data['id']))
        res = db.get_one('select * from novel_table where id=%s' % data['id'])
        # 更改用户积分
        db.update("update novel_user set num=num+2 where id=%s" % (res['userid']))
    else:
        db.update("update novel_table set state=%s where id=%s" % (data['pid'], data['id']))
    return JsonResponse({'code': '200'})


# 获取所有权限
def get_nobe(request):
    data = request.GET
    rbac = RBAC()
    data = rbac.get_role_node(data['userid'])
    return JsonResponse({'code': '200', 'data': data})


# 授权
def set_nobe(request):
    data = request.POST
    rbac = RBAC()
    data = rbac.set_role(data['roleid'], data['nobeid'])
    return JsonResponse({'code': '200', 'data': data})


# 获取所有礼品
def get_gift(request):
    db = Dd()
    data = db.get_all("select * from novel_gift")
    return JsonResponse({'code': '200', 'data': data})


# 兑换礼品
def update_gift(request):
    data = request.POST
    db = Dd()
    # 获取商品积分
    usernom = db.get_one("select * from novel_user  where id=%s" % data['userid'])
    datas = db.get_one("select * from novel_gift where id=%s" % data['pid'])
    # 修改用户积分表 如果不够 提醒积分不足
    if usernom['num'] >= int(datas['ntegral']):
        db.update("update novel_user set num=num-%s where id=%s" % (int(datas['ntegral']), data['userid']))
        usernom = db.get_one("select * from novel_user  where id=%s" % data['userid'])
        date = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')
        # print("insert into user_integral (cons_integral,add_time,resi_integral) values (%s,'%s',%s)" % (datas['ntegral'],date,usernom['num']))
        db.insert("insert into user_integral (cons_integral,add_time,resi_integral,userid) values (%s,'%s',%s,%s)" % (
        datas['ntegral'], date, usernom['num'], data['userid']))
    else:
        return JsonResponse({'code': '403', 'msg': '积分不足'})
    return JsonResponse({'code': '200', 'msg': '兑换成功'})


# 获取柱状图数据
def get_zhuzhuangtu(request):
    data = request.GET
    db = Dd()
    data = db.get_all(
        "select SUM(user_integral.cons_integral) as num,add_time from node_user left join user_integral on node_user.id=user_integral.userid where node_user.id = %s GROUP BY add_time" %
        data['userid'])
    num_list = []
    add_list = []
    for i in data:
        num_list.append(i['num'])
        add_list.append(i['add_time'])
    return JsonResponse({'code': '200', 'num_list': num_list[::-1], 'add_list': add_list[::-1]})


from dwebsocket.decorators import accept_websocket
from django.http import HttpResponse, JsonResponse
import json

# 存储连接websocket的用户
websocketlists = []


@accept_websocket
def websocketLinks(request):
    # 获取连接

    if request.is_websocket:
        # 新增 用户  连接信息
        websocketlist.append(request.websocket)
        # 监听接收客户端发送的消息 或者 客户端断开连接
        for message in request.websocket:
            break


# 发送消息
def websocketMsgs(client, msg):
    b1 = json.dumps(msg, ensure_ascii=False).encode('utf-8')
    client.send(b1)


import time


# 服务端发送消息
def sends(userid,auditid):
    print(auditid)
    if websocketlist:
        for i in websocketlist:
            db = Dd()
            if userid!=None:

                data = db.get_all(
                    "select SUM(user_integral.cons_integral) as num,add_time from node_user left join user_integral on node_user.id=user_integral.userid where node_user.id = %s GROUP BY add_time" %
                    int(userid))
                num_list = []
                add_list = []
                for j in data:
                    num_list.append(int(j['num']))
                    add_list.append(str(j['add_time']))
                mes = [{'num_list': num_list, 'add_list': add_list}]
            if auditid!=None:
                print('999')
                print(auditid)
                queue=Queue()
                data=queue.del_queue('auditlis%s' % auditid)
                print(data)
                res=db.get_one("select * from novel_table where id=%s" % data)
                mes=[{'userid':auditid,'data':res,'msg':'您有一个新的审核订单'}]
                print('8888')
            b1 = json.dumps(mes, ensure_ascii=False).encode('utf-8')
            i.send(b1)
    return HttpResponse("ok")


from apscheduler.schedulers.background import BackgroundScheduler


def testaps(request):
    data = request.GET
    # 调度器
    scheduler = BackgroundScheduler()
    # 任务存储   seconds 每秒动用多少次
    scheduler.add_job(sends, 'interval', args=(data['id'],None), seconds=10)
    scheduler.start()
    return HttpResponse("ok")
